package com.dk.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dk.mapper.UserRoleMapper;
import com.dk.pojo.User;
import com.dk.mapper.UserMapper;
import com.dk.pojo.UserRole;
import com.dk.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2021-10-29
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public User slectUserByUsername(String username) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.like("uname",username);
        User user = userMapper.selectOne(userQueryWrapper);
        return user;
    }

    @Override
    public List<User> findAll() {
        List<User> all = userMapper.findAll();
        return all;
    }

    @Override
    public boolean insertInfo(String[] rids, User user) {
        //先添加用户表,返回增加的主键
        userMapper.insertUserReturnId(user);
        Long uid = user.getUid();
        //拿到返回的主键增加用户角色中间表
        int insert= userRoleMapper.insertBatch(String.valueOf(uid),rids);
        return insert > 0;
    }

    @Override
    public boolean updateByUid(String[] rids, User user) {
        //修改用户信息
        int i = userMapper.updateById(user);
        //批量删角色中间表
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
            queryWrapper.like("uid",user.getUid());
            userRoleMapper.delete(queryWrapper);
        //批量增加角色信息表
        UserRole userRole = new UserRole();
        int insert =0;
        for (String rid : rids) {
            userRole.setUid(user.getUid().toString());
            userRole.setRid(rid);
            userRoleMapper.insert(userRole);
        }
        return insert>0;
    }

    @Override
    public boolean deleteById(Long uid) {
        //删除用户表
        int i = userMapper.deleteById(uid);
        //删除角色信息表
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("uid",uid.toString());
        int delete = userRoleMapper.delete(queryWrapper);
        return delete>0;
    }
}
